package com.sunfeng.deadletter;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import util.ConnectionUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * @Author : 清风冷影
 * @Description: 消息成为死信消息的三种情况
 * 1、消息设置了过期时间 过期了 ttl
 * 2、队列长度超长，消息被丢弃
 * 3、消息被小消费者 nack了   requeu false
 * @Date : 2021/8/25  9:35
 */
public class Consumer01 {
    //普通交换机名称
    private static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机名称
    private static final String DEAD_EXCHANGE = "dead_exchange";

    // 普通交队列名称
    private static final String NORMAL_QUEUE = "normal-queue";
    //
    private static final String DEAD_QUEUE = "dead-queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = ConnectionUtil.getChannel();
        /**
         * /声明死信和普通交换机 类型为 direct
         */
        //普通交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        // 私信交换机
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        /**
         * 声明 普通队列和私信队列
         */

        // 设置普通队列的属性
        HashMap<String, Object> params = new HashMap<>();

        params.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        params.put("x-dead-letter-routing-key", "lisi");


        // 普通队列
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, params);
        //私信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);
        /**
         *  交换机绑定队列
         */

        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String info = new String(message.getBody(), "utf-8");
            System.out.println(info);
        };

        channel.basicConsume(NORMAL_QUEUE, true, deliverCallback, (consumerTag, sig) -> {

        });

    }
}

